const axios = require('axios');

// 测试代理服务器配置功能
async function testProxyConfig() {
  const baseURL = 'http://localhost:3000';
  
  console.log('🧪 开始测试代理服务器配置功能...\n');

  try {
    // 1. 测试获取当前配置
    console.log('📋 1. 获取当前配置');
    const configResponse = await axios.get(`${baseURL}/api/v1/proxy/config/full`);
    console.log('✅ 配置获取成功');
    console.log('当前配置:', {
      mode: configResponse.data.mode,
      proxyEnabled: configResponse.data.copilot.proxy?.enabled || false,
      proxyUrl: configResponse.data.copilot.proxy?.url || 'None'
    });
    console.log('');

    // 2. 测试更新代理配置
    console.log('🔧 2. 更新代理配置');
    const updateData = {
      proxy: {
        enabled: true,
        url: 'http://proxy.example.com:8080',
        username: 'testuser',
        password: 'testpass'
      }
    };
    
    const updateResponse = await axios.put(`${baseURL}/api/v1/proxy/config/copilot`, updateData);
    console.log('✅ 代理配置更新成功');
    console.log('更新结果:', updateResponse.data.message);
    console.log('');

    // 3. 验证配置是否已保存
    console.log('🔍 3. 验证配置是否已保存');
    const verifyResponse = await axios.get(`${baseURL}/api/v1/proxy/config/full`);
    const proxyConfig = verifyResponse.data.copilot.proxy;
    
    if (proxyConfig && proxyConfig.enabled && proxyConfig.url) {
      console.log('✅ 代理配置验证成功');
      console.log('保存的配置:', {
        enabled: proxyConfig.enabled,
        url: proxyConfig.url,
        hasAuth: proxyConfig.hasAuth
      });
    } else {
      console.log('❌ 代理配置验证失败');
    }
    console.log('');

    // 4. 测试禁用代理
    console.log('🔧 4. 测试禁用代理');
    const disableData = {
      proxy: {
        enabled: false
      }
    };
    
    const disableResponse = await axios.put(`${baseURL}/api/v1/proxy/config/copilot`, disableData);
    console.log('✅ 代理禁用成功');
    console.log('禁用结果:', disableResponse.data.message);
    console.log('');

    // 5. 最终验证
    console.log('🔍 5. 最终验证');
    const finalResponse = await axios.get(`${baseURL}/api/v1/proxy/config/full`);
    const finalProxyConfig = finalResponse.data.copilot.proxy;
    
    if (finalProxyConfig && !finalProxyConfig.enabled) {
      console.log('✅ 代理禁用验证成功');
    } else {
      console.log('❌ 代理禁用验证失败');
    }

    console.log('\n🎉 代理配置功能测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error.response?.data || error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.log('\n💡 提示: 请确保后端服务已启动 (npm run start:dev)');
    }
  }
}

// 运行测试
testProxyConfig();